{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from conch.open_clip_custom import create_model_from_pretrained, tokenize, get_tokenizer\n",
    "import torch\n",
    "import os\n",
    "from PIL import Image\n",
    "from pathlib import Path\n",
    "\n",
    "# show all jupyter output\n",
    "from IPython.core.interactiveshell import InteractiveShell\n",
    "InteractiveShell.ast_node_interactivity = \"all\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "root = Path('../').resolve()\n",
    "os.chdir(root)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Load model from checkpoint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model_cfg = 'conch_ViT-B-16'\n",
    "device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n",
    "checkpoint_path = './checkpoints/CONCH/pytorch_model.bin'\n",
    "model, preprocess = create_model_from_pretrained(model_cfg, checkpoint_path, device=device)\n",
    "_ = model.eval()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Open an image and preprocess it"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = Image.open('./docs/roi1.jpg')\n",
    "image_tensor = preprocess(image).unsqueeze(0).to(device)\n",
    "image.resize((224, 224))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Load tokenizer and specify some prompts. Simplicity we just use one prompt per class (lung adenocarcinoma vs. lung squamous cell carcinoma) here instead ensembling multiple prompts / prompt templates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = get_tokenizer()\n",
    "classes = ['invasive ductal carcinoma', \n",
    "           'invasive lobular carcinoma']\n",
    "prompts = ['an H&E image of invasive ductal carcinoma', \n",
    "           'an H&E image of invasive lobular carcinoma']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenized_prompts = tokenize(texts=prompts, tokenizer=tokenizer).to(device)\n",
    "tokenized_prompts.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with torch.inference_mode():\n",
    "    image_embedings = model.encode_image(image_tensor)\n",
    "    text_embedings = model.encode_text(tokenized_prompts)\n",
    "    sim_scores = (image_embedings @ text_embedings.T * model.logit_scale.exp()).softmax(dim=-1).cpu().numpy()\n",
    "\n",
    "print(\"Predicted class:\", classes[sim_scores.argmax()])\n",
    "print(\"Normalized similarity scores:\", [f\"{cls}: {score:.3f}\" for cls, score in zip(classes, sim_scores[0])])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "conch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
